<template>
	<view class="login_center">
		<uni-forms ref="form" :modelValue="formData" :rules="rules">
			<uni-forms-item label="用户名" name="name" label-align="center">
				<uni-easyinput type="text" prefixIcon="contact" v-model="formData.name" placeholder="请输入姓名" />
			</uni-forms-item>
			<uni-forms-item label="密码" name="pwd" label-align="center">
				<uni-easyinput type="password" prefixIcon="locked" v-model="formData.pwd" placeholder="请输入密码" />
			</uni-forms-item>
		</uni-forms>
		<button @click="submit">登录</button>
	</view>
</template>

<script>
	import {
		initToken
	} from '@/tools/token.js'
	import {
		reqLogin
	} from "@/request/index.js"
	export default {
		data() {
			return {
				formData: {
					name: '',
					pwd: ''
				},
				rules: {
					name: {
						rules: [{
								required: true,
								errorMessage: '请输入用户名',
							},
							{
								minLength: 6,
								maxLength: 18,
								errorMessage: '用户名长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					},
					pwd: {
						rules: [{
								required: true,
								errorMessage: '请输入密码',
							},
							{
								minLength: 6,
								maxLength: 18,
								errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					}
				}
			}
		},
		methods: {
			async submit() {
				try {
					var res = await this.$refs.form.validate()
					try {
						var token = await reqLogin(res.name, res.pwd)
						uni.setStorage({
							data: token,
							key: "token"
						})
						uni.showToast({
							title: "登录成功",
							icon: "checkbox",
							success() {
								setTimeout(() => {
									uni.switchTab({
										url: "/pages/index/index"
									})
								}, 1500)
							}
						})
						initToken()

					} catch {
						uni.showModal({
							title: "账号或者密码不正确",
							showCancel: false
						})
					}
				} catch {

				}

			}
		}
	}
</script>
<style lang="scss">
	page {
		background-color: #259ECE;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;

		.login_center {
			background-color: white;
			padding: 50rpx;
			border-radius: 10rpx;
		}
	}
</style>
